/**
 * 路由配置文件
 * 定义应用的所有路由规则和导航守卫
 */

import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

// 导入视图组件
import LoginView from '@/views/auth/LoginView.vue'
import HomeView from '@/views/home/HomeView.vue'
import UserInfoView from '@/views/user/UserInfoView.vue'
import RegisterView from '@/views/auth/RegisterView.vue'
import PhoneLoginView from '@/views/auth/PhoneLoginView.vue'
import ForgotPasswordView from '@/views/auth/ForgotPasswordView.vue'
import PhoneReset from '@/views/user/PhoneReset.vue'
import CreateCourse from '@/views/course/CreateCourse.vue'
import CourseDetail from '@/views/course/CourseDetail.vue'
import MyCourses from '@/views/course/MyCourses.vue'
import EditCourse from '@/views/course/EditCourse.vue'
import NotificationView from '@/views/notifications/NotificationView.vue'
import AllCoursesView from '@/views/course/AllCoursesView.vue'
import AdminDashboard from '@/views/admin/AdminDashboard.vue'
import Dashboard from '@/views/admin/Dashboard.vue'
import Users from '@/views/admin/Users.vue'
import Courses from '@/views/admin/Courses.vue'
import Orders from '@/views/admin/Orders.vue'
import Settings from '@/views/admin/Settings.vue'

/**
 * 路由配置数组
 * 定义所有路由规则，包括路径、组件和元数据
 */
const routes = [
  // 认证相关路由
  {
    path: '/login',
    name: 'LoginView',
    component: LoginView,
    meta: { 
      requiresAuth: false,
      title: '登录 - 稷下书院'
    }
  },
  {
    path: '/register',
    name: 'RegisterView',
    component: RegisterView,
    meta: { 
      requiresAuth: false,
      title: '注册 - 稷下书院'
    }
  },
  {
    path: '/phone-login',
    name: 'PhoneLoginView',
    component: PhoneLoginView,
    meta: { 
      requiresAuth: false,
      title: '手机登录 - 稷下书院'
    }
  },
  {
    path: '/forgot-password',
    name: 'ForgotPasswordView',
    component: ForgotPasswordView,
    meta: { 
      requiresAuth: false,
      title: '找回密码 - 稷下书院'
    }
  },
  
  // 首页路由
  {
    path: '/',
    redirect: '/home'  // 根路径重定向到首页
  },
  {
    path: '/home',
    name: 'HomeView',
    component: HomeView,
    meta: { 
      requiresAuth: true,
      title: '首页 - 稷下书院'
    }
  },
  
  // 用户相关路由
  {
    path: '/user',
    name: 'UserInfoView',
    component: UserInfoView,
    meta: { 
      requiresAuth: true,
      title: '个人中心 - 稷下书院'
    }
  },
  {
    path: '/ai-chat',
    name: 'AIChatView',
    component: () => import('@/views/ai/AIChatView.vue'),  // 懒加载
    meta: { 
      requiresAuth: true,
      title: 'AI助手 - 稷下书院'
    }
  },
  {
    path: '/phone-reset',
    name: 'PhoneReset',
    component: PhoneReset,
    meta: { 
      requiresAuth: true,
      title: '修改手机号 - 稷下书院'
    }
  },
  
  // 课程相关路由
  {
    path: '/courses',
    name: 'courses',
    component: AllCoursesView,
    meta: { requiresAuth: true }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/course/SearchResultView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/course/create',
    name: 'CreateCourse',
    component: CreateCourse,
    meta: { 
      requiresAuth: true,
      roles: ['TEACHER', 'ADMIN'],  // 只有教师和管理员可以创建课程
      title: '创建课程 - 稷下书院'
    }
  },
  {
    path: '/course/:id',
    name: 'CourseDetail',
    component: CourseDetail,
    meta: { requiresAuth: true }
  },
  {
    path: '/my-courses',
    name: 'MyCourses',
    component: MyCourses,
    meta: { requiresAuth: true }
  },
  {
    path: '/course/edit/:id',
    name: 'EditCourse',
    component: EditCourse,
    meta: { 
      requiresAuth: true,
      roles: ['TEACHER', 'ADMIN'],  // 只有教师和管理员可以编辑课程
      title: '编辑课程 - 稷下书院'
    }
  },
  
  // 通知相关路由
  {
    path: '/notifications',
    name: 'NotificationView',
    component: NotificationView,
    meta: { requiresAuth: true }
  },
  
  // 订单相关路由
  {
    path: '/order/confirm',
    name: 'OrderConfirm',
    component: () => import('@/views/order/OrderConfirm.vue'),  // 懒加载
    meta: {
      requiresAuth: true,
      title: '订单确认 - 稷下书院',
      hideNav: true  // 隐藏导航栏
    }
  },
  {
    path: '/order/detail',
    name: 'OrderDetail',
    component: () => import('@/views/order/OrderDetail.vue'),  // 懒加载
    meta: {
      requiresAuth: true,
      title: '订单详情 - 稷下书院'
    }
  },
  
  // 课程学习路由
  {
    path: '/course/study/:scheduleId',
    name: 'CourseStudy',
    component: () => import('@/views/course/CourseStudy.vue'),  // 懒加载
    meta: { requiresAuth: true }
  },
  
  // 后台管理路由
  {
    path: '/admin',
    name: 'AdminDashboard',
    component: AdminDashboard,
    meta: { 
      requiresAuth: true,
      requiresRoot: true,
      hideNav: true,
      hideAI: true,
      hideBackToTop: true
    },
    children: [
      {
        path: '',
        redirect: '/admin/dashboard'
      },
      {
        path: 'dashboard',
        name: 'AdminDashboardHome',
        component: Dashboard,
        meta: { 
          requiresAuth: true,
          requiresRoot: true,
          hideNav: true,
          hideAI: true,
          hideBackToTop: true
        }
      },
      {
        path: 'users',
        name: 'AdminUsers',
        component: Users,
        meta: { 
          requiresAuth: true,
          requiresRoot: true,
          hideNav: true,
          hideAI: true,
          hideBackToTop: true
        }
      },
      {
        path: 'courses',
        name: 'AdminCourses',
        component: Courses,
        meta: { 
          requiresAuth: true,
          requiresRoot: true,
          hideNav: true,
          hideAI: true,
          hideBackToTop: true
        }
      },
      {
        path: 'orders',
        name: 'AdminOrders',
        component: Orders,
        meta: { 
          requiresAuth: true,
          requiresRoot: true,
          hideNav: true,
          hideAI: true,
          hideBackToTop: true
        }
      },
      {
        path: 'settings',
        name: 'AdminSettings',
        component: Settings,
        meta: { 
          requiresAuth: true,
          requiresRoot: true,
          hideNav: true,
          hideAI: true,
          hideBackToTop: true
        }
      }
    ]
  }
]

/**
 * 创建路由实例
 * 使用HTML5 History模式
 */
const router = createRouter({
  history: createWebHistory(),
  routes
})

/**
 * 全局前置守卫
 * 检查路由是否需要认证，如果需要则验证token和角色权限
 */
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  const userRole = localStorage.getItem('userRole') || sessionStorage.getItem('userRole')
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = '稷下书院' // 默认标题
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    if (!token) {
      ElMessage.error('请先登录')
      next('/login')
      return
    }
    
    // 检查用户角色权限
    if (userRole && userRole.toUpperCase() === 'ROOT') {
      // 如果是 ROOT 用户，只允许访问 /admin 路径下的页面
      if (!to.path.startsWith('/admin')) {
        ElMessage.warning('管理员只能访问后台管理页面')
        next('/admin/dashboard')
        return
      }
    } else {
      // 非 ROOT 用户不能访问需要 ROOT 权限的页面
      if (to.meta.requiresRoot) {
        ElMessage.error('无权访问')
        next('/')
        return
      }
    }
  }
  
  next()
})

export default router